<?php
// Constants
define('_ENGINE', TRUE);
define('DS', DIRECTORY_SEPARATOR);
define('PS', PATH_SEPARATOR);
set_time_limit(0);
include 'cli.php';
// Define full application path, environment, and name
defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(dirname(dirname(dirname(__FILE__))))));
defined('APPLICATION_PATH_COR') || define('APPLICATION_PATH_COR', realpath(dirname(dirname(dirname(__FILE__)))));
defined('APPLICATION_PATH_SET') || define('APPLICATION_PATH_SET', APPLICATION_PATH_COR . DS . 'settings');
defined('APPLICATION_NAME') || define('APPLICATION_NAME', 'Core');

// Application
require_once APPLICATION_PATH_COR . DS . 'libraries/Engine/Loader.php';
require_once APPLICATION_PATH_COR . DS . 'libraries/Engine/Application.php';
require_once APPLICATION_PATH_COR . DS . 'modules' . DS . 'Blogimporter' . DS . 'controllers' . DS . 'YnsRSSFeed/YnsRSS.php';
echo APPLICATION_PATH_COR . DS . 'modules' . DS . 'Blogimporter' . DS . 'controllers' . DS . 'YnsRSSFeed/YnsRSS.php';
Engine_Loader::getInstance()
        // Libraries
        ->register('Engine', APPLICATION_PATH_COR . DS . 'libraries' . DS . 'Engine')
        ->register('Zend', APPLICATION_PATH_COR . DS . 'libraries' . DS . 'Zend');


class initDatabase {

    static function _initDb() {
        $file = APPLICATION_PATH . '/application/settings/database.php';
        $options = include $file;

        $db = Zend_Db::factory($options['adapter'], $options['params']);

        // set DB to UTC timezone for this session
        switch ($options['adapter']) {
            case 'mysqli':
            case 'mysql':
            case 'pdo_mysql': {
                    $db->query("SET time_zone = '+0:00'");
                    break;
                }

            case 'postgresql': {
                    $db->query("SET time_zone = '+0:00'");
                    break;
                }

            default: {
                    // do nothing
                }
        }

        // attempt to disable strict mode
        try {
            $db->query("SET SQL_MODE = ''");
        } catch (Exception $e) {

        }
        return $db;
    }

}

//get db connection
$db = initDatabase::_initDb();
$rss = new YnsRSS();
$sql_admin = 'SELECT * FROM engine4_users WHERE level_id = 1 limit 1';
//get admin account
$admin = $db->fetchAll($sql_admin);

//log
$strLog = "";
$strLog .= "\n###############################################\n";
$strLog .= "Start get data\n";

//get categies
$sql_link = " SELECT * FROM engine4_blogimporter_links WHERE cronjob_enabled = 1 ORDER BY link_id ASC ";
$link_arr = $db->fetchAll($sql_link);
foreach ($link_arr as $link) {

    $strLog .= "Link:" . $link['link_url'] . "(" . date('Y-m-d H:i:s') . ")\n";

    //get data from remote server

        //$feed = new Zend_Feed_Rss($category['url_resource']);
        $feed = $rss->getParse(null, $link['link_url'] , null);
        $feeds = array_reverse($feed['entries']);
        foreach ($feeds as $entry) {
            $a = date('Y-m-d', $entry['pubDate']);
            $pubdate = strtotime($a);
            if(empty($entry['title'])) {
              $entry['title'] = 'Untitled Blog';
            }
            if(!empty($entry['content'])) {
              $desc = $entry['content'];
            }
            else{
              $desc = $entry['description'];
            }
            $edata = array(
                'title' => $entry['title'],
                'body' => $desc,
                'owner_type' => "user",
                'owner_id' => $link['user_id'],
                'title' => $entry['title'],
                'creation_date' => date('Y-m-d H:i:s'),
                'modified_date' => date('Y-m-d H:i:s'),
                'pub_date' => $pubdate,
                'link_detail' => $entry['link_detail']
            );
            try {
                //check blogs exist by link
                $sql_blogs = "SELECT blog_id FROM engine4_blog_blogs where link_detail = '" . $entry['link_detail'] . "'";
                $blogs = $db->fetchAll($sql_blogs);
                if (count($blogs) > 0) {
                    //do nothing
                } else {
                    $db->insert("engine4_blog_blogs", $edata);
                    $blog_id = $db->lastInsertId("engine4_blog_blogs");
                    $blog = Engine_Api::_()->getItem('blog', $blog_id);
                    $auth = Engine_Api::_()->authorization()->context;
                    $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'everyone');
                    $auth_view = "everyone";
                    $auth_comment ="everyone";
                    $viewMax = array_search($auth_view, $roles);
                    $commentMax =array_search($auth_comment, $roles);
                    foreach ($roles as $i => $role){
                    $auth->setAllowed($blog, $role, 'view', ($i <= $viewMax));
                    $auth->setAllowed($blog, $role, 'comment', ($i <= $commentMax));
                    }
                }
                $db->commit();
            } catch (Exception $e) {
                //throw $e;
            }
        }
}
$strLog .= "End get data\n";

$resource_path = APPLICATION_PATH . "/temporary/log/blog.cronjob.log";
$writer = new Zend_Log_Writer_Stream($resource_path);
$logger = new Zend_Log($writer);
$logger->info($strLog);
die;
?>
